import os
import subprocess
import sys
import tempfile
import time

from resman import resource_managers as rms

def submit(scripts_dict, pause=10):
    job_limit = rms['default'].unthrottled_limit
    
    job_list = [script_obj for script_obj in scripts_dict for i in xrange(scripts_dict[script_obj])]

    njobs_total = len(job_list) 

    while len(job_list) > 0:
        jobs_running = rms['default'].running_job_count()

        njobs_to_submit = job_limit - jobs_running
        if njobs_to_submit > len(job_list):
            njobs_to_submit = len(job_list)

        for i in xrange(njobs_to_submit):
            jobscr = job_list.pop()
            with tempfile.NamedTemporaryFile() as fp:
                fp.write(str(jobscr))
                fp.flush()
                    
                rms['default'].submit(fp.name)

        time.sleep(pause)                
        sys.stdout.write("{0}/{1} jobs submitted\r".format(njobs_total - len(job_list),
                                                          njobs_total))
        sys.stdout.flush()


    print "{0}/{0} jobs submitted\r".format(njobs_total - len(job_list),
                                                          njobs_total)
    return njobs_total




def submit_unthrottled(scripts_dict, pause=10, monitor=False):
    njobs = sum(scripts_dict.values()) 
    if njobs > resource_managers['default'].unthrottled_limit:
        return throttle.submit(scripts_dict)        

    for script_obj, count in scripts_dict.iteritems():
        for i in xrange(count):
            with tempfile.NamedTemporaryFile() as fp:
                fp.write(str(script_obj))
                fp.flush()
                
                resource_managers['default'].submit(fp.name)


    return njobs

